import type { IRouteComponentProps } from 'umi'

import { Redirect, useLocation } from 'umi'
import { ConfigProvider } from 'antd-mobile'
import { stores } from '@/stores'
import { Provider } from 'mobx-react'
import { NormalLayout } from './components'
import { YesNo } from '@/constant/enum'
import { setSiteTitle } from '@/stores/modules/site/siteInfo'

import locale from 'antd-mobile/es/locales/zh-CN'
import HelmetWrap from './components/Helmet'

const PAGE_WHITELIST: string[] = [
    '/login',
    '/register',
    '/certificate/search',
    '/certificate/result',
]

export const PAGE_ROUTE: Record<string, string> = {
    Login: '/login',
    Default: '/home',
    ChangePassword: '/personal/account',
}

const Layout = (props: IRouteComponentProps) => {
    const { pathname } = useLocation()
    const { isLogin, getUserInfo } = stores.userStore
    /** 白名单页面 */
    const isWhitelistPage = PAGE_WHITELIST.includes(pathname)
    /** 默认密码 */
    const isDefaultPassword = getUserInfo?.is_default_password === YesNo.Yes
    /** 需要重定向至修改密码页面 */
    const isNeedChangePassword = isDefaultPassword && pathname !== PAGE_ROUTE.ChangePassword

    if (isWhitelistPage) {
        return props.children
    }
    if (!isLogin) {
        return <Redirect to="/login" />
    }
    if (isNeedChangePassword) {
        return <Redirect to={PAGE_ROUTE.ChangePassword} />
    }
    if (pathname === '/') {
        return <Redirect to={PAGE_ROUTE.Default} />
    }

    return <NormalLayout {...props} />
}

export default (props: IRouteComponentProps) => {
    setTimeout(() => setSiteTitle())

    return (
        <Provider {...stores}>
            <HelmetWrap />
            <ConfigProvider locale={locale}>
                <Layout {...props} />
            </ConfigProvider>
        </Provider>
    )
}
